import React from 'react';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import {Link} from 'dva/router';
import {Button,Row,Col,Layout, Menu, Breadcrumb,Select,Icon,Form,Input,Affix,Modal,Pagination,Upload,message} from 'antd';
import reqwest from 'reqwest';
import style from '../../styles/ResetInput.less';
import inStyle from '../../styles/Info.less'
import {numvail,selectvail} from '../../utils/Validator.js'
import UpLoadGroup from '../../components/UpLoadGroup.js';
import Qiniu from 'react-qiniu'
import {beforeUpload} from '../../utils/BeforeUpLoad.js'
const Option = Select.Option;
const FormItem =Form.Item;
class AccountNew extends React.Component{
	constructor(props){
		super(props);
		this.state={
			imageUrl:null,
			files: [],
			file:'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1495096296692&di=6cd3e5536c90b559193bd15f08b4a449&imgtype=0&src=http%3A%2F%2Fimg4.duitang.com%2Fuploads%2Fitem%2F201412%2F17%2F20141217221827_F2NL4.thumb.224_0.jpeg',
			fileList:[],
			previewVisible: false,
      previewImage: '',
      token:'6qF2ejYiRzXlPoPO3eKwaWE3juLDyX5QgE1PEMJ-:rmK8666mCDYhJuGiBXqmUttPhmw=:eyJzY29wZSI6ImxlbmFnZS1jZXNoaSIsImRlYWRsaW5lIjoxNzU3MzkxNjY1fQ=='=='6qF2ejYiRzXlPoPO3eKwaWE3juLDyX5QgE1PEMJ-:rmK8666mCDYhJuGiBXqmUttPhmw=:eyJzY29wZSI6ImxlbmFnZS1jZXNoaSIsImRlYWRsaW5lIjoxNzU3MzkxNjY1fQ==',
      uploadKey: 'YOUR_CUSTOM_UPLOAD_KEY', // Optional
      prefix: 'YOUR_QINIU_KEY_PREFIX' ,// Optional
      loading:false,
		}
	}
	getBase64(img, callback) {
  		const reader = new FileReader();
  		reader.addEventListener('load', () => callback(reader.result));
  		reader.readAsDataURL(img);
	}
  handleCancel = () => this.setState({ previewVisible: false })

  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }
	handleSubmit(e){
    e.preventDefault();
		console.log(this.state.fileList)

    this.props.form.validateFields((err, values) => {
      console.log(values);
      if (!err) {
        this.loadServer({name:values.name,mobile:values.account_ltp,password:values.account_pass,admin_name:values.username})
      }else{
        message.warning('请输出必填项');
      }
    });
	}
	loadServer(params={}){
		this.setState({loading:true});
		const {fileList,file,tempFile } =this.state;
		console.log(fileList)
		reqwest({
      url: window.host+'/api/accounts/add_company',
      method: 'post',
      crossOrigin: true,
      data: {
        access_token:localStorage['token'],
        company:{name:params.name,logo:fileList[0].thumbUrl},
        admin_id:window.localStorage['userrr_id'],
        admin:{mobile:params.mobile,name:params.admin_name}
      },
      type: 'json',
    }).then((data) => {
      console.log(data);
      if(data.status=="success"){
      	message.success('更新成功', 0.5,()=>{
     		  window.location.hash='/app/account';
   		  })
      }else{
      	this.setState({loading:false});
      	message.warning(data.msg,1)
      }
    }).fail( (err, msg) =>{
    	this.setState({loading:false});
      console.log(1)
    })
	}
	handleChange(obj){
		console.log([obj.file])
  	switch(obj.file.status){
	    case 'uploading':
	      this.setState({fileList:obj.fileList});
	    break;
	    case 'error':
	       this.setState({fileList:[obj.file]});
	    break;
	    case 'removed':
	      this.setState({fileList:obj.fileList});
	    break;
  	}   
	}
	beforeUpload(file){
		console.log(file)
		// this.setState({fileList:file})
	}
	// onUpload(files){
	// 	files.map(function (f) {
 //      f.onprogress = function(e) {
 //        console.log(e.percent);
 //      };
 //    });
	// }
	componentWillMount(){
		console.log(this.props.location.query.logo);
		if(this.props.location.query.logo!==undefined){
			this.setState({
				fileList:[{
					name:'111.png',
					uid:-1,
					url:this.props.location.query.logo
				}]
			})
		}
	}
	componentDidMount(){
		// this.props.form.setFields({account_ltp:{
		// 	value:'管理员手机'
		// }})

	}
	onDrop(files){
		// console.log(files[0].preview)
		console.log(files[0])
		this.setState({file:files[0].preview,fileList:files,tempFile:files[0]})
	}
	render(){
		// console.log(window.userrr_id)
		const imageUrl = this.state.imageUrl;
		const formItemLayout = {
      labelCol: { span: 7},
      wrapperCol: { span: 17},
      // style:{minWidth:300}
    };
    const uploadButton = (
      <Row type="flex" justify="space-around" align="middle" style={{height:'100%',borderRadius:'50%'}}>
      <div style={{color:'#bbbbbb',marginTop:-8,borderRadius:'50%'}}>
        <Icon type="cloud-upload-o" style={{fontSize:54}} spin={false}/>
        <h3 className="ant-upload-text" style={{fontSize:15}}>点击上传</h3>
      </div>
      </Row>
    );
    const _img= this.state.files==null?null:<img src={this.state.files} />
		const {getFieldDecorator, getFieldsValue,setFieldsValue}=this.props.form;
		// setFieldsValue({account_ltp:this.props.location.query.mobile==undefined?'管理员手机':this.props.location.query.mobile})
		return(
				<Layout >
				<Layout.Content className={`${style.berad}`} >
					<Row>
						<Breadcrumb  className={`${style.blue_dia_none}`}>
							<Breadcrumb.Item ><span className={`${style.blue_dia}`}></span></Breadcrumb.Item>
              <Breadcrumb.Item className={`${style.bread_div} ${style.bread_div_first}`}><Link to={{pathname:'/app/Accounts',query:{current:this.props.location.query.current}}}>品牌</Link></Breadcrumb.Item>
              <Breadcrumb.Item className={`${style.bread_div}`}>新建品牌</Breadcrumb.Item>
	       		</Breadcrumb>
	       	</Row>
				</Layout.Content>
				<Layout style={{background:'#fff'}}>
				<Form hideRequiredMark={true} className={`${inStyle.ncc_left_layout}`} onSubmit={this.handleSubmit.bind(this)} >
       		<Row style={{marginTop:26}}>
						<Col className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}} >
							<FormItem {...formItemLayout} label='品牌名' >
								{getFieldDecorator('name',{
									initialValue:this.props.location.query.name,
									rules:[{required:true,message:'请输入品牌名'}]
								})(
									<Input  className={`${style.ncc_reset_input}`} placeholder='品牌名' />
								)}
							</FormItem>
							<FormItem  {...formItemLayout}  label='logo'>
								{getFieldDecorator('logo',{
									// initialValue:this.props.location.query.name,
									rules:[{required:true,message:'请选择图片'}]
								})(
			           	<Upload
					          className="avatar-uploader"
					          action="http://jsonplaceholder.typicode.com/posts/"
					          listType="picture-card"
					          fileList={this.state.fileList}
					          beforeUpload={beforeUpload}
					          onPreview={this.handlePreview.bind(this)}
					          onChange={this.handleChange.bind(this)}
					        >
					          {this.state.fileList.length == 1 ? null: uploadButton}
					        </Upload>
								)}
							</FormItem>
							<FormItem  {...formItemLayout} label='管理员姓名' >
								{getFieldDecorator('username',{
									initialValue:this.props.location.query.admin_name,
									rules:[{required:true,message:'请输入管理员姓名'}]
								})(
									<Input  className={`${style.ncc_reset_input}`} placeholder='管理员姓名' />
								)}
							</FormItem>
						 	<FormItem   {...formItemLayout} label='手机号码'>	
								{getFieldDecorator('account_ltp',{
									initialValue:this.props.location.query.mobile==undefined?undefined:this.props.location.query.mobile,
									rules:[{required:true,message:'请输入管理员手机',validator:(rule,value,callback)=>{
										numvail(rule,value,callback)
									}}]
								})(
									<Input onFocus={(e)=>{if(e.target.value=='管理员手机'){e.target.value=''};}}   className={`${style.ncc_reset_input}`} placeholder='管理员手机' />
								)}
							</FormItem>
						</Col>
					</Row>
       		<Row>
	       		<Col xl={{offset:3}} lg={{offset:2}} sm={{span :8,pull:0}} xs={{span:17,pull:3}}  >
		       		<div  style={{float:'left'}} >
		       			<FormItem >
			            <Button loading={this.state.loading} htmlType="submit" size='large' type="primary"  >
			              保存
			            </Button>
		          	</FormItem>
		          </div>
		          <div  style={{float:'left',marginLeft:10}} >
		          	<Button size='large'  >
			              <Link to={{pathname:'/app/Accounts',query:{current:this.props.location.query.current}}}>取消</Link>
			          </Button>
		          </div>
	          </Col>
          </Row>
				</Form>
				<Modal visible={this.state.previewVisible} footer={null} onCancel={this.handleCancel.bind(this)}>
          <img alt="example" style={{ width: '100%' }} src={this.state.previewImage} />
        </Modal>

			</Layout>
			</Layout>
		)
	}
}
const AccoutForm = Form.create()(AccountNew)
export default connect()(AccoutForm);